<template>
  <div class="detailOne_box">
    <n-spin :show="loading">
      <n-empty v-if="!detailData && !loading" description="暂无数据" />
      <div class="detailOne" v-if="detailData">
        <!-- {{ detailData }} -->
        <div class="detailOne_top">
          <img
            class="detailOne_top_img"
            :src="store.state.baseURL + detailData.img"
            loading="lazy"
          />
          <div class="detailOne_top_right">
            <div class="detailOne_top_right_title">
              <span class="detailOne_title">{{ detailData.title }}</span>
              <n-tag :type="detailData.class_tag == 'FREE' ? 'success' : 'error'">{{
                detailData.class_tag
              }}</n-tag>
            </div>
            <div class="detailOne_info_item">
              <span class="detailOne_info_title">上映时间：</span>
              {{ takeTimeBase(detailData.time) }}
            </div>
            <div class="detailOne_info_item">
              <span class="detailOne_info_title">评分：</span>
              <n-rate
                readonly
                size="small"
                :value="Number(detailData.average_score) / 2"
                :allow-half="true"
              />
              <span class="score_text">{{ detailData.average_score }}</span>
            </div>
            <div class="detailOne_info_item">
              <span class="detailOne_info_title">演员：</span>
              <n-ellipsis :line-clamp="1">{{ detailData.actor }}</n-ellipsis>
            </div>
            <div class="detailOne_info_item">
              <span class="detailOne_info_title">导演：</span>
              <n-ellipsis :line-clamp="1">{{ detailData.director }}</n-ellipsis>
            </div>

            <div class="detailOne_info_item">
              <span class="detailOne_info_title">简介：</span>
              <n-ellipsis expand-trigger="click" line-clamp="5" :tooltip="false">{{
                detailData.info
              }}</n-ellipsis>
            </div>
          </div>
          <div class="detailOne_top_collection">
            <n-button
              class="detailOne_top_collection_btn"
              @click="handleCollection"
              :type="detailData.collect_is ? 'primary' : 'default'"
              :size="small"
            >
            <!-- {{ changeIsCollect }}||{{  detailData.collect_is }} -->
              <span
                class="iconfont"
                :style="{ color: detailData.collect_is ? '#fff' : '#66f' }"
                >&#xe65e;</span
              >
              {{ detailData.collect_is ? "已收藏" : "未收藏" }}
            </n-button>
          </div>
        </div>
        <div class="detailOne_comment" v-if="showCommentList">
          <div class="detailOne_comment_top">
            <div class="detailOne_comment_top_left">
              <span class="detailOne_comment_title">
                <span class="iconfont">&#xe8b4;</span>
                评论区
              </span>
              <span class="detailOne_comment_num"
                >共{{ showCommentList.length }}条评论</span
              >
              <span class="detailOne_comment_num"
                >共{{ detailData.count_score }}人评价</span
              >
            </div>
            <n-radio-group v-model:value="sortTag" size="small">
              <n-radio-button value="good"> 点赞 </n-radio-button>
              <n-radio-button value="time"> 时间 </n-radio-button>
            </n-radio-group>
          </div>
          <n-divider />
          <n-empty
            size="large"
            v-if="showCommentList.length === 0"
            description="暂无评论"
          />
          <scrollview class="detailOne_comment_list" v-else>
            <div
              class="detailOne_comment_item"
              v-for="item in showCommentList"
              :key="item.id"
            >
              <div class="detailOne_comment_item_top">
                <div class="detailOne_comment_item_top_left">
                  <n-avatar
                    :src="store.state.baseURL + item.user.userImg"
                    size="large"
                    round
                  />
                  <div class="user-info">
                    <span class="detailOne_comment_item_name">{{
                      item.user.nickName || item.user.username
                    }}</span>
                    <div class="user_info_score_box">
                      <n-rate
                        v-if="item.user_score != null"
                        readonly
                        size="small"
                        :value="Number(item.user_score / 2)"
                        :allow-half="true"
                      />
                      <span v-else>暂无评分</span>
                      <span class="score_text">{{ item.user_score }}</span>
                    </div>
                  </div>
                </div>
                <span class="detailOne_comment_item_time">{{ takeTime(item.time) }}</span>
              </div>
              <div class="detailOne_comment_item_content">
                <n-ellipsis expand-trigger="click" line-clamp="3" :tooltip="false">
                  {{ item.content }}
                  <!-- {{ item }} -->
                </n-ellipsis>
              </div>
              <div class="detailOne_comment_item_bottom">
                <div class="action-buttons">
                  <n-button
                    size="small"
                    class="action-btn"
                    :class="{ active: item.isLiked }"
                    @click="handleLike(item, 'isLiked')"
                  >
                    <span class="iconfont">&#xe8ad;</span>
                    <span>{{ item.likes_count }}</span>
                  </n-button>
                  <n-button
                    size="small"
                    class="action-btn"
                    :class="{ active: item.isDisLiked }"
                    @click="handleLike(item, 'isDisLiked')"
                  >
                    <span class="iconfont reverseY">&#xe8ad;</span>
                    <span>{{ item.dislikes_count }}</span>
                  </n-button>
                </div>
              </div>
            </div>
          </scrollview>
          <n-divider />
          <div class="detailOne_comment_input">
            <div class="detailOne_comment_input_top">
              <div class="detailOne_comment_input_top_left">
                <span class="detailOne_comment_input_title">评分：</span>
                <n-rate allow-half size="large" v-model:value="videoScore" />
                <span class="score_text" v-if="videoScore != null">{{
                  videoScore * 2
                }}</span>
              </div>
              <n-popconfirm
                positive-text="确定"
                negative-text="取消"
                @positive-click="handleSetScore"
              >
                <template #trigger>
                  <n-button type="primary">设置评分</n-button>
                </template>
                确定要设置评分吗？
              </n-popconfirm>
            </div>
            <n-divider />
            <span class="detailOne_comment_input_title">评论：</span>
            <n-input
              type="textarea"
              v-model:value="commentValue"
              maxlength="100"
              show-count
              placeholder="请输入评论内容"
              class="comment-textarea"
            />
            <div class="button-group">
              <n-popconfirm
                positive-text="发表"
                negative-text="取消"
                @positive-click="handleComment"
              >
                <template #trigger>
                  <n-button type="primary">发表评论</n-button>
                </template>
                确定要发表评论吗？
              </n-popconfirm>
              <n-button secondary strong @click="commentValue = ''">清空</n-button>
            </div>
          </div>
        </div>
      </div>
    </n-spin>
  </div>
</template>

<script setup>
import {
  useMessage,
  NSpin,
  NEmpty,
  NRate,
  NEllipsis,
  NRadioGroup,
  NRadioButton,
  NInput,
  NButton,
  NAvatar,
  NDivider,
  NPopconfirm,
  NTag,
  NFloatButton,
} from "naive-ui";
import { ref, computed, onMounted } from "vue";
import { useRoute } from "vue-router";
import { takeTime, takeTimeBase } from "@/utils/base.js";
import { request } from "@/utils/request";
import { useStore } from "vuex";
const store = useStore();
const userInfo = computed(() => store.state.userInfo);
onMounted(() => {
  loading.value = true;
  InitData();
});
const InitData = () => {
  request({
    // 获取视频详情
    url: "/post_video_detail/",
    method: "POST",
    data: {
      video_id: id.value,
      user_id: userInfo.value.id,
    },
  })
    .then((res) => {
      console.log("get_video_list", res);
      detailData.value = res.data;
      changeIsCollect.value = res.data.collect_is; // 记录是否收藏
    })
    .finally(() => {
      loading.value = false;
    });
  request({
    // 获取评论
    url: "/get_comment/?video_id=" + id.value,
    method: "GET",
  }).then((res) => {
    console.log("get_comment", res);
    commentList.value = res.data.map((item) => {
      // 初始化点赞状态
      item.isLiked = false;
      item.isDisLiked = false;
      // 查找当前用户的点赞记录
      const userLike = item.like.find((like) => like.user.id === userInfo.value.id);
      // 如果找到记录，更新状态
      if (userLike) {
        item.isLiked = userLike.is_like;
        item.isDisLiked = userLike.is_dislike;
      }
      return item;
    });
  });
};
const message = useMessage();
const route = useRoute();
const id = computed(() => route.params.id);
const detailData = ref(null);
const commentList = ref([]);
const loading = ref(true);
const sortTag = ref("time");
const commentValue = ref("");
const showCommentList = computed(() => {
  if (commentList.value.length === 0) return [];
  if (sortTag.value === "good") {
    return commentList.value.sort((a, b) => b.likes_count - a.likes_count);
  } else if (sortTag.value === "time") {
    return commentList.value.sort(
      (a, b) => new Date(b.time).getTime() - new Date(a.time).getTime()
    );
  } else {
    return commentList.value;
  }
});
const handleComment = () => {
  if (commentValue.value == "") {
    message.error("评论内容不能为空");
    return;
  }

  request({
    url: "/post_comment/",
    method: "POST",
    data: {
      user_id: userInfo.value.id,
      video_id: id.value,
      content: commentValue.value,
    },
  }).then((res) => {
    if (res.code == 200) {
      message.success("评论成功");
      commentValue.value = "";
      InitData();
    } else {
      message.error(res.msg);
    }
  });
};
const videoScore = ref(null);
const handleSetScore = () => {
  if (videoScore == null) {
    message.error("请先评分");
  } else {
    // console.log("videoScore",videoScore.value)
    request({
      // 设置评分
      url: "/post_score/",
      method: "POST",
      data: {
        user_id: userInfo.value.id,
        video_id: id.value,
        score: videoScore.value * 2,
      },
    }).then((res) => {
      if (res.code == 200) {
        message.success("评分成功" + videoScore.value * 2);
        InitData();
      } else {
        message.error(res.msg);
      }
      videoScore.value = null;
    });
  }
};
// 添加点赞/踩操作处理
const handleLike = (item, type) => {
  // 更新本地状态
  const oldLiked = item.isLiked;
  const oldDisliked = item.isDisLiked;

  if (type === "isLiked") {
    item.isLiked = !item.isLiked;
    if (item.isLiked) {
      item.likes_count++;
      if (item.isDisLiked) {
        item.isDisLiked = false;
        item.dislikes_count--;
      }
    } else {
      item.likes_count--;
    }
  } else {
    item.isDisLiked = !item.isDisLiked;
    if (item.isDisLiked) {
      item.dislikes_count++;
      if (item.isLiked) {
        item.isLiked = false;
        item.likes_count--;
      }
    } else {
      item.dislikes_count--;
    }
  }

  request({
    url: "/post_like/",
    method: "POST",
    data: {
      user_id: userInfo.value.id,
      comment_id: item.id,
      isLike: item.isLiked,
      isDislike: item.isDisLiked,
    },
  }).catch(() => {
    // 请求失败时恢复原状态
    item.isLiked = oldLiked;
    item.isDisLiked = oldDisliked;
    message.error("操作失败");
  });
};
const changeIsCollect = ref(false); // 添加收藏操作处理
let reunRequest;
const handleCollection = () => {
  // 节流处理
  detailData.value.collect_is = !detailData.value.collect_is;
  if(reunRequest!=null) clearTimeout(reunRequest);
  reunRequest = setTimeout(() => {
    if (changeIsCollect.value != detailData.value.collect_is) {
      request({
        url: "/post_collect/",
        method: "POST",
        data: {
          user_id: userInfo.value.id,
          video_id: detailData.value.id,
          changeTag: detailData.value.collect_is,
        },
      }).then((res) => {
        changeIsCollect.value = detailData.value.collect_is; //更新
        if(res.code == 200) {
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      });
    }
  }, 500);
};
</script>

<style lang="scss" scoped>
@import "@/styles/base.scss";

.detailOne_box {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem 20px;

  .detailOne {
    background: #fff;
    .detailOne_top {
      position: relative;
      display: flex;
      gap: 2rem;
      border-radius: $baseBorderRadius;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      padding: 2rem;
      .detailOne_top_collection {
        position: absolute;
        right: 0;
        bottom: 0;
        margin: 2rem;
        .detailOne_top_collection_btn {
          .iconfont {
            font-size: 1.2rem;
            margin-right: 0.3rem;
          }
        }
      }
      .detailOne_top_img {
        width: 300px;
        border-radius: $baseBorderRadius;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        transition: transform 0.3s;

        &:hover {
          transform: scale(1.02);
        }
      }

      .detailOne_top_right {
        flex: 1;
        .detailOne_top_right_title {
          display: flex;
          align-items: center;
          gap: 1rem;
          font-size: 2rem;
          font-weight: bold;
          margin-bottom: 1.5rem;
          color: #333;
        }
        .detailOne_info_item {
          display: flex;
          align-items: baseline;
          margin-bottom: 0.8rem;
        }

        .detailOne_info_title {
          display: inline-block;
          min-width: 5em;
          color: #999;
          font-size: 0.9rem;
        }
      }
    }
  }
  .detailOne_comment {
    margin-top: 2rem;
    border-radius: $baseBorderRadius;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 2rem;
    .detailOne_comment_top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .detailOne_comment_title {
        font-size: 1.2rem;
        font-weight: bold;
        margin-bottom: 1rem;
      }
      .detailOne_comment_num {
        margin-left: 1rem;
        color: #999;
        font-size: 0.8rem;
      }
    }
    .detailOne_comment_list {
      display: block;
      max-height: 200vh;
      overflow-y: auto;
      margin: 1rem 0;
      .detailOne_comment_item {
        padding: 1.5rem;
        margin-bottom: 1rem;
        background: #f9f9f9;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          background: #f5f5f5;
          transform: translateY(-2px);
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
        }

        .detailOne_comment_item_top {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 1rem;

          .detailOne_comment_item_top_left {
            display: flex;
            align-items: center;
            gap: 1rem;

            .user-info {
              display: flex;
              flex-direction: column;
              gap: 0.3rem;
              .user_info_score_box {
                display: flex;
                align-items: center;
                gap: 0.3rem;
              }
              .detailOne_comment_item_name {
                font-weight: 500;
                color: #333;
              }
            }
          }

          .detailOne_comment_item_time {
            color: #999;
            font-size: 0.9rem;
          }
        }

        .detailOne_comment_item_content {
          margin: 1rem 0;
          line-height: 1.6;
          color: #666;
          font-size: 1rem;
        }

        .detailOne_comment_item_bottom {
          .action-buttons {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;

            .action-btn {
              display: flex;
              align-items: center;
              padding: 0.5rem;
              .iconfont {
                margin-right: 0.3rem;
              }
            }
            .active {
              border: 1px solid #2080f0;
              color: #2080f0;
              .iconfont {
                color: #2080f0;
              }
            }
          }
        }
      }
    }
    .detailOne_comment_input {
      margin-top: 2rem;
      padding: 1.5rem;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      .detailOne_comment_input_top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        &_left {
          display: flex;
          align-items: center;
          gap: 1rem;
        }
      }
      .detailOne_comment_input_title {
        font-size: 1.2rem;
        font-weight: bold;
      }
      .comment-textarea {
        margin: 1rem 0;
      }
      .button-group {
        display: flex;
        gap: 1rem;
        justify-content: flex-end;
      }
    }
  }
}
</style>
